# -*- coding: utf-8 -*-
from PyQt6.QtWidgets import QMessageBox,QInputDialog
from fill_table import *
from printfile import *
import sys,os
from PyQt6.QtWidgets import QApplication, QMainWindow
from gui import *


class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)

    def onAdd(self, type='row'):
        if type == 'row':
            row = self.tableWidget.rowCount()
            self.tableWidget.insertRow(row)
            for col in range(self.tableWidget.columnCount()):
                item = QtWidgets.QTableWidgetItem()
                item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                if col == 2:
                    item.setText('个')
                elif col == 3:
                    item.setText('1')
                else:
                    item.setText(' ')
                self.tableWidget.setItem(row, col, item)
        elif type == 'column':
            columnCount = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(columnCount)

    def onInsert(self, type='row'):
        if type == 'row':
            row = self.tableWidget.currentRow()
            self.tableWidget.insertRow(row)
            for col in range(self.tableWidget.columnCount()):
                item = QtWidgets.QTableWidgetItem()
                item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                if col == 2:
                    item.setText('个')
                elif col == 3:
                    item.setText('1')
                else:
                    item.setText(' ')
                self.tableWidget.setItem(row, col, item)
        elif type == 'column':
            column = self.tableWidget.currentColumn()
            self.tableWidget.insertColumn(column)

    def onDelete(self, type='row'):
        if type == 'row':
            row = self.tableWidget.currentRow()
            self.tableWidget.removeRow(row)

        elif type == 'column':
            column = self.tableWidget.currentColumn()
            self.tableWidget.removeColumn(column)
    def CalNum(self):
        """
        自动计算金额，是单价*数量
        """
        # 遍历读取所有的单元格
        for row in range(self.tableWidget.rowCount()):
            price=self.tableWidget.item(row, 3).text()
            number=self.tableWidget.item(row, 4).text()
            #这里要做约束，用正则匹配，或者重写委托逻辑来避免报错
            if price == ' ':
                price = '0'
            if number == ' ':
                number = '0'
            #简单的处理一下，防止报错
            try:
                sum=float(price)*float(number)

                #如果是整数，需要去掉后面的小数点的零
                if sum % 1 == 0:
                    self.tableWidget.item(row, 5).setText(str(int(sum)))
                else:
                    self.tableWidget.item(row,5).setText(str(format(sum,".2f")))
            except:
                reply = QMessageBox.warning(self, "警告", "请输入数字！",
                                                QMessageBox.StandardButton.Ok)
                print("请输入数字")

    def onItemClicked(self):
        self.CalNum()
        lists = []
        # 遍历读取所有的单元格
        for row in range(self.tableWidget.rowCount()):
            for col in range(self.tableWidget.columnCount()):
                lists.append(self.tableWidget.item(row, col).text())
        # 开始切片组成固定的格式
        table_lists = []
        for i in range(0, len(lists), 6):
            tmp = lists[i:i + 6]
            table_lists.append(tmp)
        # 计算所有的总数
        allnum = 0.0
        for index in table_lists:
            allnum += float(index[-1])
        # 保留2位小数点
        allnum = str(format(allnum, ".2f"))
        self.statusbar.showMessage("总价:"+allnum)

    def onCreateList(self):
        #先算一下金额
        self.CalNum()
        #创建list用来读取单元格
        lists = []
        #遍历读取所有的单元格
        for row in range(self.tableWidget.rowCount()):
            for col in range(self.tableWidget.columnCount()):
                lists.append(self.tableWidget.item(row,col).text())
        #开始切片组成固定的格式
        table_lists=[]
        for i in range(0, len(lists), 6):
            tmp=lists[i:i+6]
            table_lists.append(tmp)
        for i in range(self.tableWidget.rowCount()):
            table_lists[i].insert(0,str(i+1))
            table_lists[i].insert(1," ")
            table_lists[i].insert(1," ")
        company_name=self.lineEdit.text()
        name=self.lineEdit_2.text()
        CreatForms(name, company_name, table_lists)
        reply = QMessageBox.information(self, "完成", "已生成出库入库单！",
                                    QMessageBox.StandardButton.Ok)

    def onPrint(self):

        in_pre = "入库单-"
        out_pre = "出库单-"
        name = self.lineEdit_2.text()
        pwd_path = os.getcwd()
        in_form_path = os.path.join(pwd_path,in_pre+name+".docx")
        out_form_path = os.path.join(pwd_path,out_pre+name+".docx")
        error_flag=False
        i, in_form_num_ok = QInputDialog().getInt(self, "入库单打印",
                                          "入库单打印张数:", 2,1,4,1
                                          )
        if in_form_num_ok:
            in_form_num=i
            print(in_form_num)

        i, out_form_num_ok = QInputDialog().getInt(self, "出库单打印",
                                      "出库单打印张数:", 1, 0, 3, 1
                                      )
        if out_form_num_ok:
            out_form_num = i
            print(out_form_num)
        if in_form_num_ok:
            try:
                print_word(in_form_path,in_form_num)
            except:
                reply = QMessageBox.warning(self, "警告", "无法找到文件，请确定是否生成了入库单！",
                                        QMessageBox.StandardButton.Ok)
                error_flag=True
        time.sleep(1)
        if out_form_num_ok:
            try:
                print_word(out_form_path, out_form_num)
            except:
                reply = QMessageBox.warning(self, "警告", "无法找到文件，请确定是否生成了出库单！",
                                        QMessageBox.StandardButton.Ok)
                error_flag=True
        if error_flag:
            reply = QMessageBox.warning(self, "失败", "打印失败！请重新尝试！",
                                            QMessageBox.StandardButton.Ok)
        elif in_form_num_ok and out_form_num:
            reply = QMessageBox.information(self, "完成", "打印完成！",
                                        QMessageBox.StandardButton.Ok)
        else:
            pass
        # print(in_form_path)
        # print(out_form_path)
if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MyMainWindow()
    myWin.show()
    sys.exit(app.exec())

# from printfile import *
# pwd_path=os.getcwd()
# filename_path = os.path.join(pwd_path,"1.docx")
# print_word(filename_path,9)